const getAllStudents = () => {
    return localStorage.getItem('studentData')
        ? JSON.parse(localStorage.getItem('studentData'))
        : []
}
const setAllStudents = (data) => {
    localStorage.setItem('studentData', JSON.stringify(data))
}

// 查询数据
export const selectStudentAsync = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            const studentData = getAllStudents()
            resolve({
                code: 0,
                data: studentData
            })
        }, 500)
    })
}

// 添加数据
export const createStudentAsync = (data) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            let studentData = getAllStudents()
            studentData.push(data)
            studentData.sort((a, b) => {
                return +a.no - +b.no
            })
            setAllStudents(studentData)
            resolve({ code: 0 })
        }, 500)
    })
}

// 修改数据
export const updateStudentAsync = (data, oldData) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            let studentData = getAllStudents()
            studentData = studentData.filter((item) => item.no !== oldData.no)
            studentData.push(data)
            studentData.sort((a, b) => {
                return +a.no - +b.no
            })
            setAllStudents(studentData)
            resolve({ code: 0 })
        }, 500)
    })
}

// 删除数据
export const deleteStudentAsync = (id) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            let studentData = getAllStudents()
            studentData = studentData.filter((item) => item.no !== id)
            setAllStudents(studentData)
            resolve({ code: 0 })
        }, 500)
    })
}
